package concurrent.executors;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MonitorThreadPoolTest {

  public static void main(String[] args) {
    ThreadPoolExecutor exec = new MonitorThreadPool(0, Integer.MAX_VALUE,
        60L, TimeUnit.SECONDS,
        new SynchronousQueue<Runnable>());
    exec.submit(new DoSomething(5));
    exec.submit(new DoSomething(4));
    exec.submit(new DoSomething(3));
    exec.submit(new DoSomething(2));
    exec.submit(new DoSomething(1));
    exec.shutdown();
  }

  static class DoSomething implements Runnable {

    private int sleepTime;

    public DoSomething(int sleepTime) {
      this.sleepTime = sleepTime;
    }

    @Override
    public void run() {
      System.out.println(Thread.currentThread().getName() + " is running...sleepTime:" + sleepTime);
      try {
        if (sleepTime >= 5) {
          throw new IllegalArgumentException();
        }
        TimeUnit.SECONDS.sleep(sleepTime);
        System.out.println(Thread.currentThread().getName() + " is over.");
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

  }
}
